package com.y.comtoo.file;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import com.y.comtoo.utils.StrUtil;

public class FileAppendAlert {
	
	public static final String SourceDir = "D:\\apache-tomcat-8.5.100\\webapps\\oss\\WEB-INF\\views";
	public static final String TargetDir = "D://apache-tomcat-8.5.100/webapps/oss/WEB-INF/views2";
	

	public static void main(String[] args) throws IOException {
    	File dir = new File(SourceDir);
    	replaceDomain(dir);
	}
	
	public static void replaceDomain(File dir) throws IOException {
		/* <script>alert("static roomView.jsp ");</script> */
    	File[] flist = dir.listFiles();
    	for(File f : flist) {
    		if(f.isDirectory()) {
    			replaceDomain(f);
    		}else {
    			String oldPath = f.getAbsolutePath();
    			String newPath = oldPath.replace(SourceDir, TargetDir);
    			File nf= new File(newPath);
    			File ndir = new File(nf.getParent());
    			if(!ndir.exists()) {
    				ndir.mkdirs();
    			}
    			try {
            		List<String> lines = Files.readAllLines(Paths.get(f.getPath()));
            		/* 要写入新文件的每行数据 */
            		LinkedList<String> newLines = new LinkedList<String>();
            		Iterator<String> s = lines.iterator();
            		boolean noAppend = true;
            		String relPath = StrUtil.replaceAll(oldPath.replace(SourceDir,""),"\\", "/");
            		while(s.hasNext()) {
            			String cont = s.next();
            			if(noAppend) {
            				if(cont.contains("</head>") && cont.indexOf("--%>")<1) {
                				cont = cont.replaceFirst("</head>", "</head><script>alert('" + relPath +" ');</script>");
                				noAppend = false;
            				}else if(cont.contains("<body>") && cont.indexOf("--%>")<1) {
                				cont = cont.replaceFirst("<body>", "<body><script>alert('" + relPath  +" ');</script>");
                				noAppend = false;
            				}else if(cont.contains("</script>") && cont.indexOf("--%>")<1) {
                				cont = cont.replaceFirst("</script>", "</script><script>alert('" + relPath  +" ');</script>");
                				noAppend = false;
            				}
            			}
            			
            			newLines.add(cont);
            		}
            		if(noAppend) {
            			newLines.add("<script>alert('" + relPath  +" ');</script>");
            		}
            		Files.write(Paths.get(newPath), newLines, StandardOpenOption.CREATE);
    			}catch(Exception ex) {
    				System.out.println("处理错误的文件有：" + newPath);
    			}
    		}
    	}
	}

}
